<template>
  <div class="app-container">
    <el-card style="border-radius: 10px;">

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="计划编号" prop="planNo">
        <el-input
          v-model="queryParams.planNo"
          placeholder="请输入计划编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计划名称" prop="planName">
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入计划名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    </el-card>
    <el-card style="border-radius: 10px;margin-top: 15px">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pro:outsourcingplan:add']"
        >新增
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                v-hasPermi="['pro:outsourcingplan:export']"
              >导出</el-button>
            </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="planList" @selection-change="handleSelectionChange">

      <el-table-column label="计划编号" align="center" prop="planNo">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleInfoView(scope.row)">{{ scope.row.planNo }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="外协类型" width="120" align="center" prop="outsourceType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_outsource_type" :value="scope.row.outsourceType"/>
        </template>
      </el-table-column>
      <el-table-column label="计划名称" align="center" prop="planName"/>

      <!--      <el-table-column label="付款类型" align="center" prop="paymentType" >
              <template slot-scope="scope">
                <dict-tag :options="dict.type.erp_payment_type" :value="scope.row.paymentType"/>
              </template>
            </el-table-column>-->
      <!--      <el-table-column label="预计成本" align="center" prop="totalCost" />-->
      <el-table-column label="需求截止日期" align="center" prop="deadline">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deadline, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.status === 0">草稿</el-tag>
          <el-tag type="primary" v-else-if="scope.row.status === 1">已审批</el-tag>
          <el-tag type="warning" v-else-if="scope.row.status === 3" dffect="dark">待审批</el-tag>
          <el-tag type="danger" v-else-if="scope.row.status === 4" dffect="dark">已驳回</el-tag>
          <el-tag type="warning" v-else-if="scope.row.status === -1" dffect="dark">已中止</el-tag>
          <el-tag type="success" v-else>已完成</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleInfoView(scope.row)"
              v-hasPermi="['pro:outsourcingplan:query']"
            >查看</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-upload2"
              @click="handleApprove(scope.row)"
              v-hasPermi="['pro:outsourcingplan:approve']"
              v-show="scope.row.status === 0 || scope.row.status === 4"
            >提交</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-show="scope.row.status === 0 || scope.row.status === 4"
              v-hasPermi="['pro:outsourcingplan:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-show="(scope.row.status === 0 || scope.row.status === 4)&&scope.row.outsourceType=='Z'"
              v-hasPermi="['pro:outsourcingplan:remove']"
            >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-remove"
            @click="handlePause(scope.row)"
            v-show="scope.row.status === 1"
            v-hasPermi="['pro:outsourcingplan:pause']"
          >中止</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh"
            @click="handleResume(scope.row)"
            v-show="scope.row.status === -1"
            v-hasPermi="['pro:outsourcingplan:resume']"
          >重启</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>
    <!-- 添加或修改外协计划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-tabs type="border-card" v-model="activeTab">
        <el-tab-pane :key="1" label="外协计划信息" name="外协计划信息">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="计划编号" prop="planNo">
                  <el-input v-model="form.planNo" :readonly="optType != 'save'" placeholder="请输入计划编号"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="计划名称" prop="planName">
                  <el-input v-model="form.planName" :readonly="optType == 'view'" placeholder="请输入计划名称"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="外协类型" prop="outsourceType">
                  <el-select v-model="form.outsourceType" disabled placeholder="外协类型" >
                    <el-option
                      v-for="dict in dict.type.mes_outsource_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="生产工单号" prop="planName" v-if="form.outsourceType=='G'">
                  <el-input v-model="form.workorderCode" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="来源类型" prop="sourceType">
                  <el-select
                    v-model="form.sourceType"
                    placeholder="请选择来源类型"
                    :disabled="optType != 'save'||form.outsourceType=='G'"
                    clearable
                    @change="clearSourceCode">
                    <el-option
                      v-for="dict in dict.type.mes_outsourcing_sourcetype"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="form.sourceType == 'ORDER'">
                <el-form-item label="销售订单" prop="sourceCode">
                  <el-input v-model="form.sourceCode" placeholder="请选择销售订单" readonly label-width="100px">
                    <el-button
                      slot="append"
                      @click="handleSelectSource"
                      :disabled="optType != 'save'||form.outsourceType=='G'"
                      v-if="optType != 'view'"
                      icon="el-icon-search"
                    ></el-button>
                  </el-input>
                  <SourceSelect ref="sourceSelect" @onSelected="onSourceSelected"></SourceSelect>
                </el-form-item>
              </el-col>

            </el-row>
            <el-row v-if="form.sourceType == 'ORDER'">
              <el-col :span="12" >
                <el-form-item label="客户编码" prop="clientCode">
                  <el-input v-model="form.clientCode"  placeholder="选择销售订单返回客户编码" readonly label-width="100px">
                  </el-input>
                </el-form-item>

              </el-col>
              <el-col :span="12" >
                <el-form-item label="客户名称" prop="clientName">
                  <el-input v-model="form.clientName"  placeholder="选择销售订单返回客户名称" readonly label-width="100px">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="申请人" prop="nickName">
                  <el-input v-model="form.nickName+'（'+form.deptName+'）'" readonly placeholder="请选择申请人">
                    <el-button
                      slot="append"
                      @click="handleNickNameSelect"
                      icon="el-icon-search"
                      :disabled="optType=='view'"
                    ></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
              <UserSingleSelect
                ref="user2Select"
                :userIdFromP="form.userId"
                :dept-id-from-p="form.deptId"
                :dept-name-from-p="form.deptName"
                @onSelected="onUser2Selected"
              ></UserSingleSelect>
              <el-col :span="12">
                <el-form-item label="需求截止日期" prop="deadline">
                  <el-date-picker clearable
                                  v-model="form.deadline"
                                  type="date"
                                  :readonly="optType == 'view'"
                                  value-format="yyyy-MM-dd"
                                  placeholder="请选择需求截止日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注" prop="remarks">
                  <el-input v-model="form.remarks" type="textarea " :readonly="optType == 'view'"
                            placeholder="请输入内容"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <plan-line ref="planLine"
                     :sourceType="form.sourceType"
                     :sourceCode="form.sourceCode"
                     :plan-line-list="lineList" :outsource-type="form.outsourceType" :edit-status="form.outsourceType=='G'?'view':optType"></plan-line>

        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="isApprove" @click="approvePlan">提交审批</el-button>
        <el-button type="primary" v-if="optType == 'save' || optType == 'edit'" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import {listPlan, getPlan, delPlan, addPlan, updatePlan, approvePlan,pausePlan,resumePlan} from "@/api/mes/pro/outsourcingplan";
import PlanLine from "@/views/mes/pro/outsourcingplan/planline.vue";
import {genCode} from "@/api/system/autocode/rule";
import BomSelectSingle from "@/components/mdBomSelect/single.vue";
import Template from "@/views/print/printtemplate/list.vue";
import SourceSelect from "@/components/sourceSelect/single.vue";
import UserSingleSelect from "@/components/userSelect/single.vue";

export default {
  name: "Plan",
  components: {UserSingleSelect, SourceSelect, Template, BomSelectSingle, PlanLine},
  dicts: ['erp_payment_type', 'mes_outsource_type','mes_outsourcing_sourcetype'],
  data() {
    return {
      activeTab: '外协计划信息',
      approveFlow:[{}],
      imgUrl:'',
      oldRow: {},
      lineList: [],
      isApprove: false,
      autoGenFlag: false,
      optType: 'view',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 外协计划表格数据
      planList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      userId:null,
      deptId:null,
      deptName:null,
      nickName:null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planNo: null,
        planName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        planNo: [
          {required: true, message: "计划编号不能为空", trigger: "blur"}
        ],
        deadline: [
          {required: true, message: "需求截止日期不能为空", trigger: "blur"}
        ],
        sourceType: [
          {required: true, message: "来源类型不能为空", trigger: "blur"}
        ],
        nickName: [
          {required: true, message: "申请人不能为空", trigger: "blur"}
        ],
        sourceCode:[{ trigger: "blur",
          validator: (rule, value, callback) => {
            if (this.form.sourceType == 'ORDER'&&(value==''||value==null)) {
              callback(new Error("订单编号不能为空"));
            }else {
              callback();
            }
          }
         }],
      }
    };
  },
  created() {
    this.getList();
  },
  watch:  {
      'form.sourceCode': function (val) {
        if(this.form.planId==null||this.form.planId==undefined) {
          if (this.form.sourceType == 'ORDER' && val) {
            this.lineList = [];
          }
        }
      },

  },
  methods: {
    //人员选择返回
    onUser2Selected(row) {
      this.form.userId = row.userId;
        this.form.nickName = row.nickName;
        this.form.deptId=row.dept.deptId;
        this.form.deptName=row.dept.deptName;
        console.log(row)
    },
    handleNickNameSelect(){
      this.isBao=true;
      this.$refs.user2Select.showFlag = true;
    },
    clearSourceCode(sourceType) {
      this.form.sourceCode = null;
      if (sourceType == 'ORDER') {
        this.lineList=[];
      }
    },
    handleSelectSource() {
      this.$refs.sourceSelect.showFlag = true;
    },
    //销售订单选择弹出框
    onSourceSelected(obj) {
      if (obj) {
        this.form.sourceCode = obj.soNumber;
        this.form.clientCode=obj.clientCode;
        this.form.clientName=obj.clientName;
      }
    },
    //物料选择弹出框
    onItemSelected(obj) {
      let one = this.lineList.find(item => item.productCode === obj.itemCode);
      if (one) {
        this.$modal.msgError("该产品已添加");
        return;
      }
      let data = {
        productId: obj.itemId,
        productCode: obj.itemCode,
        productName: obj.itemName,
        specification: obj.specification,
        unitOfMeasure: obj.unitOfMeasure,
        price: obj.referencePrice,
        productQuantity: null,
        totalCost: null,
        updateStatus: false,
      }
      this.lineList.push(data);
    },
    /** 查询外协计划列表 */
    getList() {
      this.loading = true;
      listPlan(this.queryParams).then(response => {
        this.planList = response.rows;
        this.nickName=response.attachment.nickName;
        this.userId=response.attachment.userId;
        this.deptId=response.attachment.deptId;
        this.deptName=response.attachment.deptName;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sourceType: null,
        sourceCode: null,
        planId: null,
        planNo: null,
        planName: null,
        planDate: null,
        deadline: null,
        status: 0,
        remarks: null,
        totalCost: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        tenantId: null,
        outsourceType: 'Z',
        nickName: this.nickName,
        userId: this.userId,
        deptId: this.deptId,
        deptName: this.deptName,
      };
      this.resetForm("form");
      this.autoGenFlag = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.planId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      genCode('OUTSOURCE_PLAN_CODE').then(response => {
        this.form.planNo = response;
      });
      this.open = true;
      this.optType = "save";
      this.isApprove = false;
      this.lineList = [];
      this.title = "添加外协计划";
    },
    getLineList(lineList){
      let list = [];
      if(lineList) {
        lineList.forEach((obj) => {
          let data = {
            productId: obj.productId,
            productCode: obj.productCode,
            productName: obj.productName,
            specification: obj.specification,
            unitOfMeasure: obj.unitOfMeasure,
            price: obj.referencePrice,
            productQuantity: obj.productQuantity,
            totalCost: null,
            updateStatus: false,
            processCode: obj.processCode,
            processName: obj.processName
          }
          list.push(data);
        })
      }
      return list;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.optType = "edit";
      this.isApprove = false;
      const planId = row.planId || this.ids
      this.getPlanInfo(planId,'修改外协计划');
    },
    handleApprove(row) {
      this.handleInfoView(row);
      this.isApprove = true;
    },
  getPlanInfo(planId,title){
    getPlan(planId).then(response => {
      this.form = response.data;
      this.lineList = this.getLineList(response.data.lineList);
      this.open = true;
      this.title =title;
    });
  },
    /** 查看按钮操作 */
    handleInfoView(row) {
      this.reset();
      this.activeTab = '外协计划信息'
      this.isApprove = false;
      this.optType = "view";
      const planId = row.planId || this.ids
      this.getPlanInfo(planId,'查看外协计划');
    },
    lineChange(lineList) {
      this.lineList = lineList;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.lineList.length > 0) {
            let l = this.lineList.find(item => {
              return item.productQuantity == "" || item.productQuantity == null
            })
            if (l) {
              this.$modal.msgError("产品需求数量不能为空！");
              return;
            }
            this.form.lineList = this.lineList;
            if (this.form.planId != null) {
              updatePlan(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addPlan(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          } else {
            this.$modal.msgError("请添加计划产品！");
          }
        }
      });
    },
    approvePlan() {
      let approveForm = {
        planId: this.form.planId,
        status: 1,
      }
      approvePlan(approveForm).then(response => {
        this.$modal.msgSuccess("操作成功");
        this.open = false;
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const planIds = row.planId || this.ids;
      this.$modal.confirm('是否确认删除外协计划编号为"' + row.planNo + '"的数据项？').then(function () {
        return delPlan(planIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /**中止**/
    handlePause(row) {
      const planIds = row.planId ;
      this.$modal.confirm('是否确认中止外协计划编号为"' + row.planNo + '"的数据项？').then(function () {
        return pausePlan(planIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("中止成功");
      }).catch(() => {
      });
    },
    /**重启**/
    handleResume(row) {
      const planIds = row.planId ;
      this.$modal.confirm('是否确认重启外协计划编号为"' + row.planNo + '"的数据项？').then(function () {
        return resumePlan(planIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("重启成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pro/plan/export', {
        ...this.queryParams
      }, `plan_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
